<template>
<div class="header" :class="{ 'fixed-header': isFixed }">
    <div class="header-content">
        <!-- 左侧：Logo -->
        <div class="logo-container" @click="goToHome">
            <img src="@/assets/logo.png" alt="伴福熊导航" class="logo-image">
            <router-link to="/" class="pc-only"><span class="logo-text">伴福熊导航</span></router-link>
        </div>

        <!-- 中间：PC端导航菜单 -->
        <div class="nav-menu pc-only">
            <el-menu mode="horizontal" :router="true" class="menu-items" background-color="transparent"
                text-color="#606266" active-text-color="#409EFF" :default-active="activeIndex">
                <el-menu-item index="/"> <span class="menu-text"><router-link to="/"> 首页</router-link>
                    </span></el-menu-item>
                <el-menu-item index="/about"> <span class="menu-text">关于我们</span></el-menu-item>
                <el-menu-item index="/contact"> <span class="menu-text">联系我们</span> </el-menu-item>
                <el-menu-item index="/submit"> <span class="menu-text">提交网站</span> </el-menu-item>
            </el-menu>
        </div>

        <!-- 右侧：搜索框和用户操作 -->
        <div class="header-right">
            <!-- PC端搜索框和登录按钮 -->
            <div class="pc-only search-user-actions">
                <el-autocomplete v-if="!isSearchResultsPage" v-model="searchKeyword"
                    :fetch-suggestions="querySearchAsync" placeholder="搜索网站" prefix-icon="el-icon-search" size="small"
                    class="search-input" @select="handleSelect" @keyup.enter.native="handleSearch"
                    :trigger-on-focus="false" :debounce="300" popper-class="search-suggestions">
                    <template #default="{ item }">
                        <div class="search-suggestion-item">
                            <div class="website-icon" v-if="item.icon">
                                <img :src="item.icon" :alt="item.name">
                            </div>
                            <div class="website-icon" v-else>
                                <i class="el-icon-link"></i>
                            </div>
                            <div class="website-info">
                                <div class="website-name">{{ item.name }}</div>
                                <div class="website-description">{{ item.description }}</div>
                            </div>
                        </div>
                    </template>
                    <template #append>
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch"></el-button>
                    </template>
                </el-autocomplete>
                <el-button type="primary" size="small" icon="el-icon-user" class="login-button">登录</el-button>
            </div>

            <!-- 移动端搜索框 -->
            <div class="search-container mobile-only">
                <el-autocomplete v-if="!isSearchResultsPage" v-model="searchKeyword"
                    :fetch-suggestions="querySearchAsync" placeholder="搜索网站" prefix-icon="el-icon-search" size="small"
                    class="search-input" @select="handleSelect" @keyup.enter.native="handleSearch"
                    :trigger-on-focus="false" :debounce="300" popper-class="search-suggestions">
                    <template #default="{ item }">
                        <div class="search-suggestion-item">
                            <div class="website-icon" v-if="item.icon">
                                <img :src="item.icon" :alt="item.name">
                            </div>
                            <div class="website-icon" v-else>
                                <i class="el-icon-link"></i>
                            </div>
                            <div class="website-info">
                                <div class="website-name">{{ item.name }}</div>
                                <div class="website-description">{{ item.description }}</div>
                            </div>
                        </div>
                    </template>
                    <template #append>
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch"></el-button>
                    </template>
                </el-autocomplete>
            </div>

            <!-- 移动端汉堡菜单按钮 -->
            <div class="mobile-menu-toggle" @click="toggleMobileMenu">
                <i :class="['menu-icon', isMobileMenuOpen ? 'el-icon-close' : 'el-icon-s-fold']"></i>
            </div>
        </div>
    </div>

    <!-- 移动端菜单，默认隐藏 -->
    <div class="mobile-menu" v-show="isMobileMenuOpen">
        <div class="mobile-menu-items">
            <router-link to="/" class="mobile-menu-item" @click="closeMobileMenu">
                <i class="el-icon-s-home"></i> 首页
            </router-link>
            <router-link to="/about" class="mobile-menu-item" @click="closeMobileMenu">
                <i class="el-icon-info"></i> 关于我们
            </router-link>
            <router-link to="/contact" class="mobile-menu-item" @click="closeMobileMenu">
                <i class="el-icon-message"></i> 联系我们
            </router-link>
            <router-link to="/submit" class="mobile-menu-item" @click="closeMobileMenu">
                <i class="el-icon-plus"></i> 提交网站
            </router-link>
            <div class="mobile-menu-item login-item">
                <i class="el-icon-user"></i> 登录
            </div>
        </div>
    </div>
</div>
</template>

<script>
import { searchWebsites } from '@/api/index'

export default {
    name: 'HeaderComponent',
    data() {
        return {
            isFixed: true, // 初始状态设为true，使header固定显示
            scrollThreshold: 0.5, // 滚动超过页面高度的50%时取消固定
            isMoving: false,
            interval: null,
            searchKeyword: '', // 搜索关键词
            searchTimeout: null, // 搜索防抖定时器
            isMobileMenuOpen: false // 移动端菜单状态
        }
    },
    computed: {
        activeIndex() {
            // 获取当前路由路径
            const path = this.$route.path;

            // 为特定路由返回正确的索引
            if (path.startsWith('/search')) {
                // 搜索页不高亮任何菜单
                return '';
            }
            // 其他页面返回完整路径
            return path;
        },
        // 判断当前是否在搜索结果页
        isSearchResultsPage() {
            return this.$route.path === '/search';
        }
    },
    mounted() {
        window.addEventListener('scroll', this.handleScroll);
        // 初始化时设置header为固定状态
        this.isFixed = true;
    },
    beforeUnmount() {
        window.removeEventListener('scroll', this.handleScroll);
        if (this.interval) {
            clearInterval(this.interval);
        }
        if (this.searchTimeout) {
            clearTimeout(this.searchTimeout);
        }
    },
    methods: {
        // 点击logo跳转到首页
        goToHome() {
            if (this.$route.path !== '/') {
                this.$router.push('/');
            }
        },
        handleScroll() {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const windowHeight = window.innerHeight;
            // 逻辑取反：滚动超过阈值时取消固定，否则保持固定
            this.isFixed = scrollTop <= windowHeight * this.scrollThreshold;
        },
        backToTop() {
            if (this.isMoving) return;
            const start = window.pageYOffset;
            const end = 0;
            const duration = 150;
            const startTime = Date.now();
            this.isMoving = true;

            const easeInOutQuad = (t, b, c, d) => {
                t /= d / 2;
                if (t < 1) return c / 2 * t * t + b;
                t--;
                return -c / 2 * (t * (t - 2) - 1) + b;
            };

            this.interval = setInterval(() => {
                const time = Date.now() - startTime;
                const val = easeInOutQuad(time, start, end - start, duration);
                window.scrollTo(0, val);
                if (time >= duration) {
                    window.scrollTo(0, end);
                    clearInterval(this.interval);
                    this.isMoving = false;
                }
            }, 16);
        },
        // 搜索建议
        querySearchAsync(queryString, callback) {
            if (queryString.trim() === '') {
                callback([]);
                return;
            }

            // 清除之前的定时器
            if (this.searchTimeout) {
                clearTimeout(this.searchTimeout);
            }

            // 设置新的定时器，防抖处理
            this.searchTimeout = setTimeout(async () => {
                try {
                    const res = await searchWebsites(queryString);
                    if (res && res.data) {
                        // 限制显示的建议数量
                        const suggestions = res.data.slice(0, 5).map(item => {
                            return {
                                ...item,
                                value: item.name // 必须有value属性，用于显示
                            };
                        });
                        callback(suggestions);
                    } else {
                        callback([]);
                    }
                } catch (error) {
                    console.error('获取搜索建议失败:', error);
                    callback([]);
                }
            }, 300);
        },
        // 选择搜索建议
        handleSelect(item) {
            if (item && item.url) {
                this.openWebsite(item.url);
            }
        },
        // 执行搜索
        handleSearch() {
            if (this.searchKeyword.trim() === '') {
                return;
            }

            console.log('Header执行搜索:', this.searchKeyword);

            // 导航到搜索结果页面
            this.$router.push({
                path: '/search',
                query: { searchText: this.searchKeyword }
            }).catch(err => {
                console.error('路由跳转错误:', err);
            });

            // 清空搜索关键词
            this.searchKeyword = '';
        },
        // 打开网站
        openWebsite(url) {
            window.open(url, '_blank');
        },
        // 切换移动端菜单
        toggleMobileMenu() {
            this.isMobileMenuOpen = !this.isMobileMenuOpen;
            // 打开菜单时禁止滚动
            if (this.isMobileMenuOpen) {
                document.body.style.overflow = 'hidden';
            } else {
                document.body.style.overflow = '';
            }
        },
        // 关闭移动端菜单
        closeMobileMenu() {
            this.isMobileMenuOpen = false;
            document.body.style.overflow = '';
        }
    }
}
</script>

<style scoped>
.header {
    background-color: #ffffff;
    padding: 0;
    width: 100%;
    height: 60px;
    z-index: 1000;
    transition: all 0.3s ease;
}

.fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
}

.header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    max-width: 1600px;
    margin: 0 auto;
    padding: 0 20px;
    height: 60px;
    position: relative;
}

.logo-container {
    display: flex;
    align-items: center;
    width: 200px;
    cursor: pointer;
}

.logo-container a {
    display: flex;
    align-items: center;
    text-decoration: none;
    color: #303133;
}

.logo-image {
    height: 32px;
}

.logo-text {
    font-weight: 520;
}

/* 中间导航菜单 */
.nav-menu {
    flex: 1;
    display: flex;
    justify-content: center;
}

.menu-items {
    border-bottom: none;
    display: flex;
    margin: 0 auto;
}

.menu-text {
    font-size: 14px;
    font-weight: 700;
}

/* 只保留底部颜色条样式 */
.el-menu--horizontal>.el-menu-item.is-active {
    border-bottom: 2px solid #409EFF;
}

/* 确保所有el-menu-item具有相同的样式 */
.el-menu--horizontal>.el-menu-item {
    height: 60px;
    line-height: 60px;
}

/* 右侧区域 */
.header-right {
    display: flex;
    align-items: center;
}

/* 搜索框和登录按钮容器 */
.search-user-actions {
    display: flex;
    align-items: center;
}

.search-container {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
}

.search-input {
    width: 220px;
    margin-right: 15px;
}

.login-button {
    white-space: nowrap;
}

/* 搜索建议样式 */
.search-suggestion-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
}

.search-suggestion-item .website-icon {
    width: 24px;
    height: 24px;
    margin-right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.search-suggestion-item .website-icon img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.search-suggestion-item .website-icon i {
    font-size: 20px;
    color: #909399;
}

.search-suggestion-item .website-info {
    flex: 1;
    overflow: hidden;
}

.search-suggestion-item .website-name {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.search-suggestion-item .website-description {
    font-size: 12px;
    color: #909399;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 移动端菜单切换按钮 */
.mobile-menu-toggle {
    display: none;
    width: 40px;
    height: 40px;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.menu-icon {
    font-size: 24px;
    color: #303133;
    transition: all 0.3s;
}

/* 移动端菜单 */
.mobile-menu {
    position: fixed;
    top: 60px;
    left: 0;
    width: 100%;
    height: calc(100vh - 60px);
    background-color: #ffffff;
    z-index: 999;
    overflow-y: auto;
    transition: all 0.3s ease;
}

.mobile-menu-items {
    display: flex;
    flex-direction: column;
    padding: 20px;
}

.mobile-menu-item {
    display: flex;
    align-items: center;
    padding: 15px;
    color: #303133;
    font-size: 16px;
    font-weight: 500;
    text-decoration: none;
    border-bottom: 1px solid #ebeef5;
    transition: all 0.3s;
}

.mobile-menu-item i {
    margin-right: 10px;
    font-size: 20px;
}

.mobile-menu-item:hover,
.mobile-menu-item:active {
    background-color: #f5f7fa;
    color: #409EFF;
}

.login-item {
    margin-top: 20px;
    background-color: #f0f8ff;
    border-radius: 4px;
    border: none;
    color: #409EFF;
}

/* PC端和移动端显示控制 */
.pc-only {
    display: flex;
}

.mobile-only {
    display: none;
}

/* 响应式样式 */
@media (max-width: 768px) {
    .header {
        height: 60px;
    }

    .header-content {
        padding: 0 15px;
        justify-content: space-between;
        height: 60px;
    }

    .logo-container {
        width: auto;
        margin-right: 10px;
    }

    .logo-text {
        display: none;
    }

    .logo-image {
        height: 28px;
    }

    .mobile-menu-toggle {
        display: flex;
    }

    .pc-only {
        display: none;
    }

    .mobile-only {
        display: flex;
    }

    .search-container {
        flex: 1;
    }

    .search-input {
        width: 100%;
        margin-right: 0;
    }

    /* 搜索建议在移动端的样式调整 */
    .search-suggestions {
        width: 90vw !important;
        max-width: none !important;
        left: 5vw !important;
    }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
    .search-input {
        max-width: 180px;
    }

    .mobile-menu-item {
        padding: 12px;
        font-size: 15px;
    }
}

a {
    text-decoration: none;
}
</style>